package com.superlc.ssm.core.shiro.realm;

import com.superlc.ssm.core.shiro.util.ShiroByteSource;
import com.superlc.ssm.modular.sys.model.SysPermission;
import com.superlc.ssm.modular.sys.model.SysRole;
import com.superlc.ssm.modular.sys.model.UserInfo;
import com.superlc.ssm.modular.sys.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * @ProjectName: ssm$
 * @Package: com.superlc.ssm.config$
 * @ClassName: SysShiroRealm$
 * @Description: java类作用描述
 * @Author: super
 * @CreateDate: 2018/8/16$ 12:25$
 * @UpdateUser: 更新者
 * @UpdateDate: 2018/8/16$ 12:25$
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class SysShiroRealm extends AuthorizingRealm {

    @Resource
    private UserInfoService userInfoService ;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->SysShiroRealm.doGetAuthorizationInfo()-----"+principalCollection.getRealmNames());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo = (UserInfo)principalCollection.getPrimaryPrincipal();
        for(SysRole role:userInfo.getRoleList()){
            //添加可用角色
            if(role.getAvailable()){
                authorizationInfo.addRole(role.getRole());
                for(SysPermission permission:role.getPermissions()){
                    //添加可用权限
                    if(permission.getAvailable()){
                        authorizationInfo.addStringPermission(permission.getPermission());
                    }
                }
            }

        }
        return authorizationInfo;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //添加缓存后会优先从缓存中 获取 authenticationInfo
        // 缓存中存在时 这个方法不会调用 本方法 在这里给session设置userInfo值 可能不会赋值上去

        ///rememberMe 的用户不会调用这个方法
        logger.info("SysShiroRealm.doGetAuthenticationInfo()");
        logger.info("登陆token： "+authenticationToken.toString());
        String username = (String)authenticationToken.getPrincipal();
        logger.info(authenticationToken.getCredentials().toString());
        UserInfo userInfo = userInfoService.getUserAllInfoByUserName(username);
        logger.info("从数据库取出用户信息："+userInfo.toString());
        if(userInfo == null){
            return null;
        }
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        session.setAttribute("userInfo",userInfo);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                //用户名
                userInfo,
                //密码
                userInfo.getPassword(),
                //salt=username+salt
                //ByteSource.Util.bytes(userInfo.getCredentialsSalt()),
                new ShiroByteSource(userInfo.getCredentialsSalt()),
                //这里序列化报错，难怪我一直不知道什么问题，还是要打断点看最后一个cause
                //realm name
                getName()
        );

        return authenticationInfo;
    }
}
